package com.wechat.api;

import java.util.Date;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.wechat.model.Address;
import com.wechat.thread.MyThread;
import com.wechat.util.MyUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class BaiduAPI {
	/**
	 * 根据位置信息获取周边
	 * 
	 * @throws Exception
	 * @dagewang 2017年11月23日
	 */
	public String nearbyGet(Map<String, String> map) throws Exception {
		MyUtil myUtil = MyUtil.getMyUtil();
		String x = map.get("Location_X");
		String y = map.get("Location_Y");
		String query = "美食";
		String ak = "MEImaUFQFKo7LScaTc7wv0tuObTlSb9V";
		//将地理位置信息加入到集合
		Address address=new Address();
		address.setAddress(map.get("Label"));
		address.setxAndY(x+","+y);
		address.setUsername(map.get("FromUserName"));
		address.setCdate(new Date());
		MyThread.address.add(address);
		String sendGet = myUtil.sendGet("http://api.map.baidu.com/place/v2/search", "query=" + query + "&location=" + x
				+ "," + y + "&radius_limit=true&" + "output=json&scope=2&coord_type=1&" + "radius=1200&ak=" + ak + "");
		JSONObject fromObject = JSONObject.fromObject(sendGet);
		String message = fromObject.getString("message");
		int status = fromObject.getInt("status");
		if (status != 0 || !message.equals("ok")) {
			return "很抱歉占时,没法获取您周围的美食信息.";
		}
		JSONArray arr = JSONArray.fromObject(fromObject.get("results"));
		if (arr == null || arr.size() == 0) {
			return "您的附近没有餐厅哦!";
		}
		StringBuffer sb = new StringBuffer();
		int size = arr.size();
		for (int i = 0; i < size; i++) {
			JSONObject j = arr.getJSONObject(i);
			JSONObject jo = j.getJSONObject("detail_info");
			Integer distance = jo.getInt("distance");
			Object overall_rating = jo.get("overall_rating");
			Object tel = j.get("telephone");
			if (overall_rating == null){
				overall_rating = "暂无评分";
			}
			if (tel == null){
				tel = "无";
			}
			sb.append(i + 1 + "." + j.get("name") + "\n距离您:" + distance + "米,综合评分:" + overall_rating + "\n地址:"
					+ j.get("address") + "\n联系电话:" + tel + "\n");

		}
		return sb.toString();
	}
}
